package com.deductive.netty.tcp;

import com.deductive.netty.tcp.handler.TcpMessageHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class NettyTcpServerInitializer extends ChannelInitializer<SocketChannel> {

    @Autowired
    private TcpMessageHandler tcpMessageHandler;

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();

        // --- JSON over TCP Pipeline ---

        // Inbound handlers (Receiving data)
        // 1. Frame Decoder: Splits the stream of bytes by newline characters (\n).
        //    Each complete line is a full JSON message.
        pipeline.addLast(new LineBasedFrameDecoder(1024 * 1024)); // Max message size: 1MB

        // 2. String Decoder: Converts the byte frames (from the frame decoder) into Java Strings.
        pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));

        // Outbound handlers (Sending data)
        // 3. String Encoder: Converts outgoing Java Strings into bytes.
        pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));

        // 4. Custom Business Logic Handler
        pipeline.addLast(tcpMessageHandler);
    }
}
